import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { fas } from '@fortawesome/free-solid-svg-icons';
import './style.css';
import { useAuthStore } from '@/stores/auth';

// 处理 AttaTransport.addReadyCallback 方法未实现问题
if (window.AttaTransport && !window.AttaTransport.addReadyCallback) {
    window.AttaTransport.addReadyCallback = function(callback) {
        console.warn('AttaTransport.addReadyCallback 方法未实现，使用空实现替代');
        setTimeout(callback, 0);
    };
}

// 初始化FontAwesome
library.add(fas);

const app = createApp(App);
const pinia = createPinia();

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}

// 注册FontAwesome组件
app.component('font-awesome-icon', FontAwesomeIcon);

// 全局错误处理器
app.config.errorHandler = (err, instance, info) => {
    console.error('[全局错误]', err, '组件实例:', instance, '错误信息:', info);

    // 检查是否是认证相关错误
    if (err.message?.includes('accessToken') || err.message?.includes('authStore')) {
        router.push('/login').catch(() => {});
    }

    if (app.config.globalProperties.$message) {
        app.config.globalProperties.$message.error(
            err.message || '应用出现错误，请稍后重试'
        );
    }
};

// 显示加载状态
function showLoading() {
    const loadingInstance = app.config.globalProperties.$loading?.({
        lock: true,
        text: '应用初始化中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });

    return loadingInstance || {
        close: () => {}
    };
}

// 应用初始化
const initApp = async () => {
    let loading = null;

    try {
        console.log('[应用初始化] 开始');
        loading = showLoading();

        // 先初始化Pinia和路由
        app.use(pinia);
        app.use(ElementPlus, {
            locale: zhCn,
            size: 'default'
        });
        app.use(router);

        // 获取authStore实例
        const authStore = useAuthStore();

        if (!authStore) {
            throw new Error('无法初始化认证存储');
        }

        // 初始化认证状态
        await authStore.initialize();

        // 动态导入authApi以避免循环依赖
        if (authStore.accessToken) {
            const { authApi } = await import('@/api/auth');
            authApi.setAuthHeader(authStore.accessToken);
        }

        // 确保用户数据有效
        if (authStore.isAuthenticated && !authStore.user) {
            try {
                await authStore.fetchUser();
            } catch (err) {
                console.warn('获取用户信息失败:', err);
                if (err.response?.status === 401) {
                    await authStore.logout();
                }
            }
        }

        app.mount('#app');
        console.log('[应用初始化] 完成');
    } catch (err) {
        console.error('[应用初始化] 失败:', err);

        // 即使初始化失败也挂载应用，以便显示错误界面
        app.mount('#app');

        if (app.config.globalProperties.$message) {
            app.config.globalProperties.$message.error(
                err.response?.data?.message ||
                err.message ||
                '应用初始化失败，请刷新页面'
            );
        }
    } finally {
        setTimeout(() => {
            loading?.close?.();
        }, 300);
    }
};

// 启动应用
initApp();